import React, { useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import NavBar from '@/components/NavBar'
import { List, DatePicker, Drawer, Toast, Modal } from 'antd-mobile'
import { useDispatch, useSelector } from 'react-redux'
import { editUser } from '@/store/actions/profile'
import classNames from 'classnames'
import EditInput from './components/EditInput'
import EditList from './components/EditList'
import { editUserInfo, editPhoto, logout } from '@/store/actions/profile'
import dayjs from 'dayjs'
import { useHistory } from 'react-router'
const alert = Modal.alert
const Item = List.Item

export default function EditUser() {
  const history = useHistory()
  const dispatch = useDispatch()
  // 获取上传文件表单
  const fileRef = useRef(null)
  // 控制修改昵称和简介的抽屉的显示隐藏
  const [open, setOpen] = useState({
    type: '',
    visible: false,
  })
  // 控制修改头像和性别的抽屉的显示与隐藏
  const [listOpen, setListOpen] = useState({
    type: '',
    visible: false,
  })

  const profile = useSelector((state) => state.profile.profile)
  // 获取用户个人资料
  useEffect(() => {
    dispatch(editUser())
  }, [dispatch])

  // 关闭抽屉事件
  const onClose = () => {
    setOpen({
      type: '',
      visible: false,
    })
    setListOpen({
      type: '',
      visible: false,
    })
  }

  // 定义头像性别的渲染数据
  const config = {
    photo: [
      {
        title: '拍照',
        onClick: () => {
          console.log('拍照')
        },
      },
      {
        title: '本地选择',
        onClick: () => {
          fileRef.current.click()
        },
      },
    ],
    gender: [
      {
        title: '男',
        onClick: () => {
          // 修改性别
          onFormCommit('gender', 0)
        },
      },
      {
        title: '女',
        onClick: () => {
          // 修改性别
          onFormCommit('gender', 1)
        },
      },
    ],
  }

  // 抽屉表单数据提交
  const onFormCommit = async (type, value) => {
    await dispatch(editUserInfo(type, value))
    // 提示修改成功
    Toast.success('修改成功', 1)
    // 关闭抽屉
    onClose()
  }

  // 上传图片表单事件
  const onAvatarChange = async (e) => {
    // 获取选中的图片文件
    const file = e.target.files[0]
    // 生成表单数据
    const formData = new FormData()
    formData.append('photo', file)
    await dispatch(editPhoto(formData))
    // 上传成功
    Toast.success('上传成功', 1)
    // 关闭抽屉
    onClose()
  }

  // 修改生日
  const onChangeBirthday = (e) => {
    onFormCommit('birthday', dayjs(e).format('YYYY-MM-DD'))
  }

  // 退出登录
  const logoutFn = () => {
    alert('温馨提示', '你确定要退出吗？', [
      { text: '取消' },
      {
        text: '确定',
        onPress: async () => {
          await dispatch(logout())
          // 跳转到登录页
          history.push('/login')
        },
      },
    ])
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人信息</NavBar>
        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img src={profile.photo} alt="" />
                </span>
              }
              arrow="horizontal"
              onClick={() => {
                setListOpen({
                  type: 'photo',
                  visible: true,
                })
              }}
            >
              头像
            </Item>
            <Item
              extra={profile.name}
              arrow="horizontal"
              onClick={() => {
                setOpen({
                  type: 'name',
                  visible: true,
                })
              }}
            >
              昵称
            </Item>
            <Item
              onClick={() => {
                setOpen({
                  type: 'intro',
                  visible: true,
                })
              }}
              extra={
                <span
                  className={classNames('intro', profile.intro ? 'normal' : '')}
                >
                  {profile.intro || '未填写'}
                </span>
              }
              arrow="horizontal"
            >
              简介
            </Item>
          </List>
          <List className="profile-list">
            <Item
              onClick={() => {
                setListOpen({
                  type: 'gender',
                  visible: true,
                })
              }}
              extra={profile.gender === 0 ? '男' : '女'}
              arrow="horizontal"
            >
              性别
            </Item>
            <DatePicker
              mode="date"
              title="生日"
              value={new Date(profile.birthday)}
              minDate={new Date(1900, 1, 1)}
              maxDate={new Date()}
              onChange={onChangeBirthday}
            >
              <Item extra={profile.birthday} arrow="horizontal">
                生日
              </Item>
            </DatePicker>
          </List>
          {/* 文件选择框，用于头像图片的上传 */}
          <input ref={fileRef} type="file" hidden onChange={onAvatarChange} />
        </div>
        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={logoutFn}>
            退出登录
          </button>
        </div>
      </div>
      {/*控制修改昵称和简介的 抽屉 */}
      <Drawer
        className="drawer"
        position="right"
        sidebar={
          open.visible ? (
            <EditInput
              onCommit={onFormCommit}
              onClose={onClose}
              type={open.type}
            ></EditInput>
          ) : (
            ''
          )
        }
        open={open.visible}
        children={''}
      />
      {/* 控制修改头像和性别的抽屉 */}
      <Drawer
        className="drawer-list"
        position="bottom"
        children={''}
        sidebar={
          listOpen.visible && (
            <EditList
              config={config}
              onClose={onClose}
              type={listOpen.type}
            ></EditList>
          )
        }
        open={listOpen.visible}
        onOpenChange={onClose}
      ></Drawer>
    </div>
  )
}
